import 'package:dio/dio.dart';
import 'package:get/get.dart' hide Response;
import 'package:getx_app/app/routes/app_pages.dart';
import 'package:sp_util/sp_util.dart';

class DioUtil {
  static void initDio() {
    Get.lazyPut(() {
      BaseOptions options = BaseOptions(baseUrl: "https://gw.kaike123.com", connectTimeout: 10000, receiveTimeout: 3000);
      Dio _dio = Dio(options);
      _dio.interceptors.add(CustomInterceptor());
      return _dio;
    }, fenix: true);
  }
}

class CustomInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    print('REQUEST[${options.method}] => PATH: ${options.path}');
    var token = SpUtil.getString("token");
    if (token != null && token.isNotEmpty) {
      options.headers['Authorization'] = "Bearer $token";
    }
    return super.onRequest(options, handler);
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    print('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
    if (err.response?.statusCode == 401) {
      Get.offAllNamed(Routes.LOGIN);
    }
    super.onError(err, handler);
  }
}
